package org.freedoit.server.service.task;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;

import org.freedoit.common.data.FreeDoitSendRequest;
import org.freedoit.common.data.FreeDoitSyncDataResponse;
import org.freedoit.common.shared.SharedTask;
import org.freedoit.server.om.Task;
import org.freedoit.server.service.ServiceManager;
import org.freedoit.server.util.Utils;

public class SendTaskServlet extends AbstractTaskServlet<FreeDoitSendRequest, FreeDoitSyncDataResponse> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5491581135229913652L;

	protected FreeDoitSyncDataResponse createResponseObject() {
		// TODO Auto-generated method stub
		return new FreeDoitSyncDataResponse();
	}

	protected void processRequest(
			ServiceContext<FreeDoitSendRequest, FreeDoitSyncDataResponse> context,
			Long timestamp) {
		// TODO Auto-generated method stub
		FreeDoitSendRequest reuqestObject = context.getRequestObject();
		FreeDoitSyncDataResponse responseObject = context.getResponseObject();
		if (reuqestObject == null) {
			responseObject.setCode(FreeDoitSyncDataResponse.CODE_INVALID_REQUEST);
			return;
		}
		
		// Process Task
		List<SharedTask> taskList = reuqestObject.getTasks();
		List<SharedTask> taskResponseList = new LinkedList<SharedTask>();
		Task task = null;
		Timestamp dateLastModifyTime = new Timestamp(timestamp);
		if (taskList != null && !taskList.isEmpty()) {
			for (SharedTask sharedTask : taskList) {
				task = Utils.fromSharedData(sharedTask);
				
				// Update Task
				ServiceManager.updateTask(task, context.getCurrentClientId(), dateLastModifyTime);
				
				// Create repsonse
				taskResponseList.add(new SharedTask(sharedTask.getSerialNo(), task.getTaskId()));
			}
			
			responseObject.setTasks(taskResponseList);
		}
		
		responseObject.setCode(FreeDoitSyncDataResponse.CODE_OK);
		responseObject.setTimestamp(timestamp);
		
	}
	
	protected Type getRequestType() {
		return new com.google.gson.reflect.TypeToken<FreeDoitSendRequest>() {  
		}.getType();
	}

}
